package top.heliming.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import top.heliming.bean.PageResult;
import top.heliming.bean.User;
import top.heliming.service.UserService;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/05/21 下午 11:23
 */
@Controller
@CrossOrigin(origins = "*", allowCredentials = "true")
public class HelloController {

  @Autowired
  private UserService userService;

  @ResponseBody
  @GetMapping("hello")
  public User hello() {

    User user = this.userService.queryById(1L);
    System.out.println(user);
    return user;
  }

  @GetMapping("/all")
  public String all(
      ModelMap model) { // 查询用户
    List<User> users = this.userService.queryAll();
    // 放入模型
    model.addAttribute("users", users);
    // 返回模板名称（就是classpath:/templates/目录下的html文件名）
    return "users";
  }

  @PostMapping("/page")
  @ResponseBody
  public PageResult list(
      @RequestBody PageResult pageResult) { // 查询用户
    //select * from student limit(curPage-1)*pageSize,pageSize;
    int pagesize = pageResult.getPagesize();
    int pagenum = (pageResult.getCurrent() - 1) * pageResult.getPagesize();
    String key = pageResult.getKey();
    List<User> users = this.userService.list(pagenum, pagesize, key);
    int count = this.userService.count(key);
    if (users == null || users.size() == 0) {
      return null;
    }
    pageResult.setData(users);
    pageResult.setStatus("success");
    pageResult.setCount(this.userService.count(key));
    return pageResult;
  }

}
